﻿/* Copyright 2007-2009 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using dnAnalytics.Statistics.Distributions;

namespace dnAnalytics.Mcmc
{
    /// <summary>
    /// Rejection sampling produces samples from distribition P by sampling from a proposal distribution Q
    /// and accepting/rejecting based on the density of P and Q. The density of P and Q don't need to
    /// to be normalized, but we do need that for each x, P(x) < Q(x).
    /// </summary>
    /// <typeparam name="T">The type of samples this sampler produces.</typeparam>
    public class RejectionSampler<T> : McmcSampler<T>
    {
        /// <summary>
        /// Evaluates the density function of the sampling distribution.
        /// </summary>
        private readonly Density<T> mPdfP;

        /// <summary>
        /// Evaluates the density function of the proposal distribution.
        /// </summary>
        private readonly Density<T> mPdfQ;

        /// <summary>
        /// A function which samples from a proposal distribution.
        /// </summary>
        private readonly GlobalProposalSampler<T> mProposal;

        /// <summary>
        /// Constructs a new rejection sampler using the default <see cref="System.Random"/> random number generator.
        /// </summary>
        /// <param name="pdfP">The density of the distribution we want to sample from.</param>
        /// <param name="pdfQ">The density of the proposal distribution.</param>
        /// <param name="proposal">A method that samples from the proposal distribution.</param>
        public RejectionSampler(Density<T> pdfP, Density<T> pdfQ, GlobalProposalSampler<T> proposal)
        {
            mPdfP = pdfP;
            mPdfQ = pdfQ;
            mProposal = proposal;
        }

        /// <summary>
        /// Returns a sample from the distribution P.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">When the algorithms detects that the proposal
        /// distribution doesn't upper bound the target distribution.</exception>
        public override T Sample()
        {
            while (true)
            {
                // Get a sample from the proposal.
                T x = mProposal();
                // Evaluate the density for proposal.
                double q = mPdfQ(x);
                // Evaluate the density for the target density.
                double p = mPdfP(x);
                // Sample a variable between 0.0 and proposal density.
                double u = ContinuousUniform.Sample(RandomNumberGenerator, 0.0, q);

                mSamples++;

                if (q < p)
                {
                    throw new ArgumentOutOfRangeException(Properties.Resources.ProposalDistributionNoUpperBound);
                }
                if (u < p)
                {
                    mAccepts++;
                    return x;
                }
            }
        }
    }
}